package com.star.bookstore.member.exception;

import com.star.bookstore.common.excoption.CodeEnum;
import com.star.bookstore.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.star.bookstore.member")
public class MemberExceptionControllerAdvice {

    @ExceptionHandler(value = MyBatisSystemException.class)
    public R handleRepeatException(MyBatisSystemException e){

        System.out.println("捕捉到异常");

        log.error("数据重复异常{},异常类型：{}" + e.getMessage(),e.getClass());

        return R.error(CodeEnum.REPEAT_EXCEPTION.getCode(),CodeEnum.REPEAT_EXCEPTION.getMessage());

    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public R handleFormatException(HttpMessageNotReadableException e){

        System.out.println("捕捉到异常");

        log.error("错误请求异常{},异常类型：{}" + e.getMessage(),e.getClass());

        return R.error(CodeEnum.FORMAT_EXCEPTION.getCode(),CodeEnum.FORMAT_EXCEPTION.getMessage());

    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){

        System.out.println("捕捉到异常");

        log.error("数据校验出现问题{},异常类型：{}" + e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            System.out.println(fieldError.getField() + "  " +fieldError.getDefaultMessage());
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(CodeEnum.VAILD_EXCEPTION.getCode(),CodeEnum.VAILD_EXCEPTION.getMessage()).put("data",errorMap);
    }


    @ExceptionHandler(value = Exception.class)
    public R handException(Exception e){
        log.error("未知异常{},异常类型：{}" + e.getMessage(),e.getClass());
        return R.error(CodeEnum.UNKNOW_EXCEPTION.getCode(),CodeEnum.UNKNOW_EXCEPTION.getMessage());
    }


}
